import router from './router'
import store from './store'

// 
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style


import { getToken } from './utils/auth' // get token from cookie

const whiteList = ['/login'] // no redirect whitelist

function changeTittle(to) {
    if (to.meta.title) {
        document.title = to.meta.title
    }
}

router.beforeEach(async(to, from, next) => {
    // start progress bar
    NProgress.start()

    // determine whether the user has logged in
    const hasToken = getToken()

    if (hasToken) {
        if (to.path === '/login') {
            // if is logged in, redirect to the home page

            next({ path: '/' })
            changeTittle(to)
            NProgress.done()
        } else {
            const hasGetUserInfo = store.getters.name
            if (hasGetUserInfo) {
                changeTittle(to)
                next()
            } else {
                try {
                    // get user info
                    await store.dispatch('getInfo')
                        // get now semseter
                    await store.dispatch('getNewSemester')
                    changeTittle(to)

                    next()
                } catch (error) {
                    // remove token and go to login page to re-login
                    await store.dispatch('resetToken')
                    this.message.error('登录信息有误或已失效')
                    next(`/login`)
                    changeTittle(to)
                    NProgress.done()
                }
            }
        }
    } else {
        /* has no token*/

        if (whiteList.indexOf(to.path) !== -1) {
            // in the free login whitelist, go directly
            changeTittle(to)

            next()
        } else {
            // other pages that do not have permission to access are redirected to the login page.

            next(`/login`)
            changeTittle(to)

            NProgress.done()
        }
    }
})

router.afterEach(() => {
    // finish progress bar
    NProgress.done()
})